﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using ZenSystemService.Api.Data;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.DTOs.ProductType;
using ZenSystemService.Api.Entities;

namespace ZenSystemService.Api.Services
{
    public class ProductTypeService
    {
        private readonly ApplicationDbContext _context;
        private readonly IMapper _mapper;

        public ProductTypeService(ApplicationDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<IEnumerable<ProductTypeQueryResultDTO>> GetAllProductTypesAsync()
        {
            var productTypes = await _context.ProductTypes.Include(t => t.DeviceType).ToListAsync();
            return _mapper.Map< IEnumerable<ProductTypeQueryResultDTO>>(productTypes);
        }

        public async Task<ProductTypeQueryResultDTO?> GetProductTypeByIdAsync(int id)
        {
            var productType = await _context.ProductTypes.Include(p => p.DeviceType)
                .FirstOrDefaultAsync(p => p.ProductTypeId == id);
            if(productType != null) { 
                return _mapper.Map<ProductTypeQueryResultDTO>(productType);
            }
            return null;
        }

        public async Task<ProductTypeQueryResultDTO> CreateProductTypeAsync(ProductTypeCreateRequestDTO productType)
        {
            var productTypeEntity = _mapper.Map<ProductType>(productType);
            var deviceType = await _context.DeviceTypes.FirstOrDefaultAsync(d => d.DeviceTypeId == productType.DeviceTypeId);
            productTypeEntity.DeviceType = deviceType;
            await _context.ProductTypes.AddAsync(productTypeEntity);
            _context.SaveChanges();
            return _mapper.Map<ProductTypeQueryResultDTO>(productTypeEntity);
        }

        public async Task<ProductTypeQueryResultDTO> UpdateProductTypeAsync(ProductTypeUpdateRequestDTO productType)
        {
            var productTypeEntity = await _context.ProductTypes.FirstOrDefaultAsync(t => t.ProductTypeId == productType.ProductTypeId);
            if(productTypeEntity == null)
            {
                return null;
            }
            productTypeEntity.UpdateFrom(productType);
            _context.Entry(productTypeEntity).State = EntityState.Modified;
            int count = await _context.SaveChangesAsync();
            return _mapper.Map<ProductTypeQueryResultDTO>(productTypeEntity);
        }

        public async Task<bool> DeleteProductTypeAsync(int id)
        {
            var deviceType = await _context.ProductTypes.FindAsync(id);
            if (deviceType != null)
            {
                _context.ProductTypes.Remove(deviceType);
                int count = await _context.SaveChangesAsync();
                return count > 0 ? true : false;
            }
            else
            { 
                return false;
            }
        }
    }
}
